/**
 * MongoDB连接配置文件
 * 用于配置和初始化MongoDB连接
 */

const mongoose = require('mongoose');
const { logInfo, logError } = require('../logger');

// MongoDB连接配置
const mongoConfig = {
  development: {
    uri: process.env.MONGO_URI || 'mongodb://localhost:27017/spiritual_insight_dev',
    options: {}
  },
  test: {
    uri: process.env.MONGO_URI || 'mongodb://localhost:27017/spiritual_insight_test',
    options: {}
  },
  production: {
    uri: process.env.MONGO_URI || 'mongodb://localhost:27017/spiritual_insight',
    options: {}
  }
};

// 获取当前环境配置
const env = process.env.NODE_ENV || 'development';
const config = mongoConfig[env];

/**
 * 初始化MongoDB连接
 */
async function initMongoDB() {
  try {
    // 设置Mongoose调试模式（仅在开发环境）
    if (env === 'development') {
      mongoose.set('debug', true);
    }
    
    // 连接MongoDB
    await mongoose.connect(config.uri, config.options);
    
    logInfo('MongoDB连接成功', { 
      environment: env,
      uri: config.uri 
    });
    
    // 连接事件监听
    mongoose.connection.on('connected', () => {
      logInfo('MongoDB连接已建立');
    });
    
    mongoose.connection.on('error', (err) => {
      logError('MongoDB连接错误', { error: err.message });
    });
    
    mongoose.connection.on('disconnected', () => {
      logInfo('MongoDB连接已断开');
    });
    
    // 优雅关闭
    process.on('SIGINT', async () => {
      await mongoose.connection.close();
      logInfo('MongoDB连接已关闭');
      process.exit(0);
    });
    
    return true;
  } catch (error) {
    logError('MongoDB连接失败', { 
      error: error.message,
      environment: env,
      uri: config.uri
    });
    throw error;
  }
}

module.exports = {
  initMongoDB,
  mongoose
};